package com.example.heimashop.view.activity;

import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.lifecycle.ViewModelProvider;

import com.example.heimashop.base.BaseActivity;
import com.example.heimashop.database.CartDao;
import com.example.heimashop.databinding.ActivityProductDetailBinding;
import com.example.heimashop.model.CartItem;
import com.example.heimashop.model.ProductDetail;
import com.example.heimashop.utils.GlideUtils;
import com.example.heimashop.utils.ToastUtils;
import com.example.heimashop.viewmodel.ProductViewModel;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.List;

/**
 * 商品详情页面
 * 页面9: ProductDetailActivity - 商品详情页面
 */
public class ProductDetailActivity extends BaseActivity<ActivityProductDetailBinding> {

    private ProductViewModel viewModel;
    private int productId;
    private ProductDetail currentProduct;
    private CartDao cartDao;

    @Override
    protected ActivityProductDetailBinding getViewBinding() {
        return ActivityProductDetailBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        viewModel = new ViewModelProvider(this).get(ProductViewModel.class);
        productId = getIntent().getIntExtra("productId", 0);
        cartDao = new CartDao(this);

        binding.banner.addBannerLifecycleObserver(this)
                .setIndicator(new CircleIndicator(this));

        // 配置 WebView
        setupWebView();
    }

    /**
     * 配置 WebView 以显示 HTML 内容
     */
    private void setupWebView() {
        WebSettings webSettings = binding.webviewDetail.getSettings();

        // 启用 JavaScript
        webSettings.setJavaScriptEnabled(true);

        // 自适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        // 禁用缩放
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDisplayZoomControls(false);

        // 设置布局算法
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        // 图片自动加载
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setBlockNetworkImage(false);

        // 允许混合内容（HTTPS页面加载HTTP资源）
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        // 设置缓存
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);

        // 设置编码
        webSettings.setDefaultTextEncodingName("UTF-8");

        // 使用硬件加速以支持大内容
        binding.webviewDetail.setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null);

        // 设置 WebChromeClient
        binding.webviewDetail.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                android.util.Log.d("ProductDetail", "WebView加载进度: " + newProgress + "%");
                if (newProgress == 100) {
                    // 加载完成后延迟调整高度
                    view.postDelayed(() -> adjustWebViewHeight(view), 300);
                }
            }
        });

        // 设置 WebViewClient
        binding.webviewDetail.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 在WebView内打开链接
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                android.util.Log.d("ProductDetail", "WebView页面加载完成");
                // 页面加载完成后执行JavaScript加载懒加载图片
                view.loadUrl("javascript:window.onload();");
                // 延迟调整WebView高度以适应内容
                view.postDelayed(() -> adjustWebViewHeight(view), 500);
            }
        });
    }

    /**
     * 动态调整WebView高度以适应内容
     */
    private void adjustWebViewHeight(final WebView webView) {
        webView.post(() -> {
            // 通过JavaScript获取实际内容高度
            webView.evaluateJavascript(
                "(function() { return document.body.scrollHeight; })();",
                value -> {
                    try {
                        int contentHeight = Integer.parseInt(value);
                        float density = getResources().getDisplayMetrics().density;
                        int heightInDp = (int) (contentHeight * density);

                        android.util.Log.d("ProductDetail", "内容高度(px): " + contentHeight + ", 转换后(dp): " + heightInDp);

                        android.view.ViewGroup.LayoutParams params = webView.getLayoutParams();
                        if (heightInDp > 0) {
                            params.height = heightInDp;
                            webView.setLayoutParams(params);
                            android.util.Log.d("ProductDetail", "WebView高度已设置为: " + heightInDp + "dp");
                        } else {
                            // 使用备用方法
                            int contentHeightOld = webView.getContentHeight();
                            float scale = webView.getScale();
                            int height = (int) (contentHeightOld * scale * density);

                            android.util.Log.d("ProductDetail", "使用备用方法，高度: " + height);

                            if (height > 0) {
                                params.height = height;
                                webView.setLayoutParams(params);
                            }
                        }
                    } catch (Exception e) {
                        android.util.Log.e("ProductDetail", "调整WebView高度失败: " + e.getMessage());
                    }
                }
            );
        });
    }

    @Override
    protected void initData() {
        viewModel.productDetailLiveData.observe(this, productDetail -> {
            if (productDetail != null) {
                showProductDetail(productDetail);
            }
        });

        viewModel.errorLiveData.observe(this, error -> {
            if (error != null) {
                ToastUtils.showShort(this, error);
            }
        });

        viewModel.getProductDetail(productId);
    }

    @Override
    protected void initListener() {
        binding.ivBack.setOnClickListener(v -> finish());

        // 加入购物车
        binding.btnAddCart.setOnClickListener(v -> {
            if (currentProduct != null) {
                addToCart();
            } else {
                ToastUtils.showShort(this, "商品信息加载中，请稍后");
            }
        });

        // 立即购买
        binding.btnBuyNow.setOnClickListener(v -> {
            if (currentProduct != null) {
                buyNow();
            } else {
                ToastUtils.showShort(this, "商品信息加载中，请稍后");
            }
        });
    }

    /**
     * 加入购物车
     */
    private void addToCart() {
        // 获取商品图片（优先使用small logo）
        String imageUrl = currentProduct.getPics() != null && !currentProduct.getPics().isEmpty()
                ? currentProduct.getPics().get(0).getPicsSmaUrl()
                : "";

        CartItem cartItem = new CartItem(
                currentProduct.getGoodsId(),
                currentProduct.getGoodsName(),
                currentProduct.getGoodsPrice(),
                imageUrl,
                1  // 默认数量为1
        );

        long result = cartDao.addToCart(cartItem);
        if (result != -1) {
            ToastUtils.showShort(this, "已加入购物车");
            android.util.Log.d("ProductDetail", "商品已加入购物车: " + currentProduct.getGoodsName());
        } else {
            ToastUtils.showShort(this, "加入购物车失败");
        }
    }

    /**
     * 立即购买
     */
    private void buyNow() {
        // 先加入购物车
        String imageUrl = currentProduct.getPics() != null && !currentProduct.getPics().isEmpty()
                ? currentProduct.getPics().get(0).getPicsSmaUrl()
                : "";

        CartItem cartItem = new CartItem(
                currentProduct.getGoodsId(),
                currentProduct.getGoodsName(),
                currentProduct.getGoodsPrice(),
                imageUrl,
                1
        );

        cartDao.addToCart(cartItem);

        // 跳转到购物车页面（通过切换MainActivity的tab）
        ToastUtils.showShort(this, "请在购物车中完成结算");

        // 返回到主页面并切换到购物车tab
        android.content.Intent intent = new android.content.Intent();
        intent.putExtra("switchToCart", true);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void showProductDetail(ProductDetail detail) {
        android.util.Log.d("ProductDetail", "显示商品详情: " + detail.getGoodsName());

        // 保存当前商品信息
        this.currentProduct = detail;

        // 商品名称
        binding.tvName.setText(detail.getGoodsName());

        // 商品价格
        binding.tvPrice.setText(String.format(java.util.Locale.CHINA, "¥%.2f", detail.getGoodsPrice()));

        // 简短描述（从HTML中提取文本）
        String description = extractTextFromHtml(detail.getGoodsIntroduce());
        if (description.isEmpty()) {
            description = "查看下方商品详情";
        }
        binding.tvDescription.setText(description);

        // 销量（API中没有销量字段，隐藏或显示占位）
        binding.tvSales.setVisibility(android.view.View.GONE);

        // 库存
        binding.tvStock.setText(String.format(java.util.Locale.CHINA, "库存: %d件", detail.getGoodsNumber()));

        android.util.Log.d("ProductDetail", "准备加载HTML，长度: " +
            (detail.getGoodsIntroduce() != null ? detail.getGoodsIntroduce().length() : 0));

        // 使用 WebView 渲染完整的 HTML 内容
        if (detail.getGoodsIntroduce() != null && !detail.getGoodsIntroduce().isEmpty()) {
            loadHtmlContent(detail.getGoodsIntroduce());
        } else {
            loadHtmlContent("<p style='text-align:center;color:#999;padding:20px;'>暂无商品详情</p>");
        }

        // 设置轮播图
        if (detail.getPics() != null && !detail.getPics().isEmpty()) {
            android.util.Log.d("ProductDetail", "设置轮播图，数量: " + detail.getPics().size());
            setupBanner(detail.getPics());
        } else {
            android.util.Log.w("ProductDetail", "没有轮播图数据");
        }
    }

    /**
     * 从HTML中提取简短的文本描述
     */
    private String extractTextFromHtml(String html) {
        if (html == null || html.isEmpty()) {
            return "";
        }
        // 移除HTML标签，只保留文本
        String text = html.replaceAll("<[^>]*>", "");
        // 移除多余的空白字符
        text = text.replaceAll("\\s+", " ").trim();
        // 限制长度
        if (text.length() > 100) {
            text = text.substring(0, 100) + "...";
        }
        return text;
    }

    /**
     * 加载 HTML 内容到 WebView
     * 添加样式使 HTML 显示更美观
     */
    private void loadHtmlContent(String htmlContent) {
        android.util.Log.d("ProductDetail", "========== 开始加载HTML内容 ==========");
        android.util.Log.d("ProductDetail", "HTML内容长度: " + (htmlContent != null ? htmlContent.length() : 0));
        android.util.Log.d("ProductDetail", "WebView可见性: " + binding.webviewDetail.getVisibility());
        android.util.Log.d("ProductDetail", "WebView宽高: " + binding.webviewDetail.getWidth() + "x" + binding.webviewDetail.getHeight());

        if (htmlContent == null || htmlContent.isEmpty()) {
            htmlContent = "<p style='text-align:center;color:#999;padding:20px;'>暂无商品详情</p>";
        }

        // 处理协议相对URL：将 // 替换为 https://
        htmlContent = htmlContent.replace("src=\"//", "src=\"https://");
        htmlContent = htmlContent.replace("data-src=\"//", "data-src=\"https://");
        htmlContent = htmlContent.replace("href=\"//", "href=\"https://");

        android.util.Log.d("ProductDetail", "URL替换完成，准备构建完整HTML");

        // 确保WebView可见
        binding.webviewDetail.setVisibility(android.view.View.VISIBLE);

        // 创建完整的 HTML 文档，添加样式
        String styledHtml = "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">" +
                "<style>" +
                "* { " +
                "  margin: 0; " +
                "  padding: 0; " +
                "  box-sizing: border-box; " +
                "}" +
                "body { " +
                "  font-size: 14px; " +
                "  line-height: 1.6; " +
                "  color: #333; " +
                "  word-wrap: break-word; " +
                "  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; " +
                "  background-color: #fff; " +
                "}" +
                "img { " +
                "  max-width: 100% !important; " +
                "  width: 100% !important; " +
                "  height: auto !important; " +
                "  display: block; " +
                "  margin: 0 auto; " +
                "  vertical-align: middle; " +
                "}" +
                "p { " +
                "  margin: 0; " +
                "  padding: 0; " +
                "}" +
                "div { " +
                "  margin: 0; " +
                "  padding: 0; " +
                "}" +
                "h1, h2, h3, h4, h5, h6 { " +
                "  margin: 12px 0 8px 0; " +
                "  font-weight: bold; " +
                "}" +
                "ul, ol { " +
                "  margin: 8px 0; " +
                "  padding-left: 20px; " +
                "}" +
                "table { " +
                "  width: 100%; " +
                "  border-collapse: collapse; " +
                "  margin: 10px 0; " +
                "}" +
                "table, th, td { " +
                "  border: 1px solid #ddd; " +
                "  padding: 8px; " +
                "}" +
                "a { " +
                "  color: #1890ff; " +
                "  text-decoration: none; " +
                "}" +
                ".lazyimg { " +
                "  width: 100%; " +
                "}" +
                "</style>" +
                "<script>" +
                // 处理懒加载图片
                "window.onload = function() {" +
                "  var images = document.getElementsByTagName('img');" +
                "  for(var i = 0; i < images.length; i++) {" +
                "    var dataSrc = images[i].getAttribute('data-src');" +
                "    if(dataSrc && !images[i].src) {" +
                "      images[i].src = dataSrc;" +
                "    }" +
                // 移除width和height属性，使用CSS控制
                "    images[i].removeAttribute('width');" +
                "    images[i].removeAttribute('height');" +
                "  }" +
                "};" +
                "</script>" +
                "</head>" +
                "<body>" +
                htmlContent +
                "</body>" +
                "</html>";

        // 使用 loadDataWithBaseURL 以支持图片加载
        binding.webviewDetail.loadDataWithBaseURL(
                "https://image.suning.cn/",  // 设置baseURL支持相对路径
                styledHtml,
                "text/html",
                "UTF-8",
                null
        );

        android.util.Log.d("ProductDetail", "WebView加载HTML完成，HTML总长度: " + styledHtml.length());
    }

    private void setupBanner(List<ProductDetail.Pic> pics) {
        binding.banner.setAdapter(new BannerImageAdapter<ProductDetail.Pic>(pics) {
            @Override
            public void onBindView(BannerImageHolder holder, ProductDetail.Pic data, int position, int size) {
                GlideUtils.loadImage(holder.itemView.getContext(), data.getPicsBigUrl(), holder.imageView);
            }
        });
    }

    @Override
    protected void onDestroy() {
        // 清理 WebView 防止内存泄漏
        if (binding != null && binding.webviewDetail != null) {
            binding.webviewDetail.loadDataWithBaseURL(null, "", "text/html", "UTF-8", null);
            binding.webviewDetail.clearHistory();
            binding.webviewDetail.clearCache(true);
            binding.webviewDetail.onPause();
            binding.webviewDetail.removeAllViews();
            binding.webviewDetail.destroy();
        }
        super.onDestroy();
    }
}
